<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Feihuo extends FaXingBase
{

    public function register($params)
    {
        $cid = $params['cid'];
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);
        $check_sign = $this->createSign($sign_data,$this->extdata['Loginkey']);

        if($check_sign != $sign){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['uid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }

    public function order($order)
    {
        $game_name = get_game_filed($order['gid'],'name');
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();


        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['Paykey']);

        $time = time();
        $data = [
            'server_id'=>$role['sid'] ?? '0',//区服id
            'server_name'=>$role['sid'] ?? '0',//区服名称
            'role_id' => $role['role_id'] ?? 0,//角色id
            'role_name' => $role['role_name'] ?? "",//角色名称
            'goods_id' => rand(000000,999999),//商品id
            'goods_name' => $order['goods_name'],//商品名称
            'uid' => $account[1],//商品名称
            'money' => (int) $order['amount'],//金额 整数：元
            'order_id' => $order['order_no'],
            'ext' =>$order['order_no']."|".$sign ,
            'time' => $time
        ];
        $data['sign'] = $this->createSign($data,$this->extdata['Paykey']);
        return $data;
    }

    public function check_order($params)
    {
        $ord_arr = explode("|",$params['ext']);
        $order_no = $ord_arr[0];
        $sign = $ord_arr[1];

        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['Paykey']);

        if($order_sign != $sign){
            echo json_encode(['status'=>3,'message'=>'签名错误']);exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params,$this->extdata['Paykey'])){
            echo json_encode(['status'=>3,'message'=>'签名错误']);exit;
        }


        if($order['amount'] != $params['money']){
            echo json_encode(['status'=>3,'message'=>'金额错误']);exit;
        }
        $order->trade_no = $params['order_id'];
        $order->save();

        return $order;
    }

    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['code'=>1,'message'=>'Success']) :  json_encode(['status'=>3,'message'=>'未知错误']);
        exit;
    }

    public function create_role($params)
    {
        $url = "https://www.feihuo.com/gamesApi/report/role";

        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];
        $account = explode("_",$player['account']);
        $time = time();
        $data = [
            'api_key' => $this->extdata['ApiKey'],
            'timestamp' => $time,
            'user_id' =>(int) $account[1],
            'sid' =>(int) $params['sid'],
            'name' => $params['role_name'],
            'create_time' => $time,
            'ygx_data' => $third_data['ygx_data']
        ];
        $data['sign'] = $this->createSign($data,$this->extdata['SecretKey']);
        $res = curlRequest($url,$data,[],"POST",'form');
        echo $res['data'];exit;
    }

    private function createSign($params, $key) {
        ksort($params);
        $params['key'] = $key;
        $md5Str = http_build_query($params);

        return md5($md5Str);
    }

    protected function check_sign($params, $key)
    {
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);

        $check_sign = $this->createSign($sign_data,$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}